from django.shortcuts import render
from shops.models import Dishes,Shops
from users.models import UserModel
from orders.models import Shopping_trolley,Order,Address,OrderGoods
from rest_framework.views import APIView,Response
from rest_framework.viewsets import ViewSet
from utils.force_login import check_login
from utils.jwt_token import verification_token
from rest_framework.viewsets import ModelViewSet
from orders.serializer import OrderSer,Order_GoodSer
import time,random,redis
from catering_takeout import settings
from alipay import AliPay

class Add_to_Cart(APIView):
    @check_login
    def post(self,request,id):
        dishes = id
        shops = request.data.get('shops_id')
        user = request.user.id
        print(">>>>",dishes,shops,user)
        dishes_ser = Dishes.objects.get(id = dishes)
        try:
            shopping_tro = Shopping_trolley.objects.get(dishes=dishes,shops=shops,user=user)
            shopping_tro.dishes_count += 1
            shopping_tro.save()
            return Response({'code': 200, 'msg': '商品已存在数量+1'})
        except Exception as e:
            print(e)
            Shopping_trolley.objects.create(dishes_id=dishes,shops_id=shops,user_id=user,dishes_price=dishes_ser.dishes_price,is_coupon_id=1)
            return Response ({'code':200,'msg':'添加商品成功'})


class Shopping_all(ViewSet):
    @check_login
    def get_cart(self,request,id):
        user_id = request.user.id
        print(user_id)
        shopping = Shopping_trolley.objects.filter(user_id=user_id)
        print(shopping)
        alist = []
        for i in shopping:
            if i.shops_id == id:
                dishes = Dishes.objects.get(id=i.dishes_id)
                shops = Shops.objects.get(id=i.shops_id)
                goods ={
                    'id':i.id,
                    'dishes_id':dishes.id,
                    'dishes_name':dishes.dishes_name,
                    'dishes_price':dishes.dishes_price,
                    'dishes_picture':dishes.dishes_picture,
                    'shops_id':shops.id,
                    'shops_name':shops.shops_name,
                    'sending_fee':shops.sending_fee,
                    'dishes_count':i.dishes_count,
                }
                alist.append(goods)
        return Response({'code':200,'msg':'获取购物车数据成功','data':alist})
    def del_cart(self,request,id):
        Shopping_trolley.objects.get(id=id).delete()
        return Response ({'code':200,'msg':'删除成功'})


    def jia_cart(self,request,id):
        shopping = Shopping_trolley.objects.get(id=id)

        shopping.dishes_count +=1
        shopping.save()
        return Response({'code':200,'msg':'成功'})

    def jian_cart(self,request,id):
        shopping = Shopping_trolley.objects.get(id=id)
        if not shopping.dishes_count == 0:
            shopping.dishes_count -=1
            shopping.save()
            return Response({'code':200,'msg':'成功'})
        return Response({'code':204,'msg':'该商品数量已经为0'})


# 读取app私钥
app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH,'r').read()

# 读取支付宝公钥
zfb_public_key_string = open(settings.ZFB_PUBLIC_KEY_PATH,'r').read()

# 支付宝
class AlipayObject():
    def __init__(self):
        self.alipay = AliPay(
            appid='2021000119635013',
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=zfb_public_key_string,
            app_notify_url=None,
            sign_type='RSA2',
            debug=True
        )


# 生成订单
class OrderModeView(ModelViewSet):
    queryset = Order.objects.all()
    serializer_class = Order_GoodSer
    @check_login
    def create(self, request, *args, **kwargs):
        user_id = request.user.id
        shopping_info = request.data.get('shopping_info')

        print('shopping_info=============>', shopping_info)
        print('shopping_info=============>', type(shopping_info))
        # address_id = request.data.get('address_id')
        #
        # if not address_id:
        #     return Response({'message': '请确认收货地址', 'code': 400})

        order_id = int(time.time() * 1000000) + user_id + random.randint(10000, 99999)
        z_price = 0
        z_num = 0
        freight = 5
        shops_id = 0
        print('asdasdasd')
        # 创建订单
        order = Order.objects.create(order_id=order_id, user_id=user_id, total_count=z_num, total_amount=z_price,addr_id=1,
                             freight =freight ,pay_method=1, pay_status=0)

        try:
            for i in shopping_info:
                print('单个饭菜的信息',i)
                print('order_id',order_id)
                OrderGoods.objects.create(
                    dishes_id=i['dishes_id'],
                    count=i['dishes_count'],
                    price=i['dishes_price'],
                    order_id=order_id
                )
                z_num += int(i['dishes_count'])  # 商品总数量
                shops_id = i['shops_id']
                print('============商品的数量', int(i['dishes_count']))
                z_price += (float(i['dishes_price']) * int(i['dishes_count'])) # 商品总价格
            order.total_count = z_num
            order.total_amount = z_price
            order.shop_id = shops_id
            order.save()
        except Exception as e:
            print('报错信息是===>', e)
            return Response({'message':'写入菜品订单报错'})

        print('==================================>')
        for i in shopping_info:
            print('单个购物车数据',i)
            Shopping_trolley.objects.get(id=i['id']).delete()
            print('删除成功')


        return Response({'msg': '生成订单成功', 'code': 200})


# 获取订单
class OrderView(ModelViewSet):
    queryset = Order.objects.all()
    serializer_class = OrderSer
    @check_login
    def list(self, request, *args, **kwargs):
        user_id = request.user.id
        print('user_id',user_id)

        # try:
            # 根据用户id获取订单
        order1_list = []
        order1 = Order.objects.filter(user=user_id, pay_status=0).all()  # 未支付订单
        for i in order1:
            data_ = {
                'shop_id':i.shop_id,
                'order_id': i.order_id,
                'order_num': i.total_count,
                'order_price': i.total_amount,
            }
            order_dishes = OrderGoods.objects.filter(order_id=i.order_id).all()
            dishes_list = []
            for j in order_dishes:
                data = {
                    'dishes_id': j.dishes.id,
                    'name': j.dishes.dishes_name,
                    'dishes_price': j.price,
                    'num': j.count,
                    'img': j.dishes.dishes_picture
                }
                # print('dat', data)
                dishes_list.append(data)
            data_['order_dishes'] = dishes_list
            order1_list.append(data_)
            # print('================>order1_list', order1_list)

        order2_list = []
        order2 = Order.objects.filter(user_id=user_id, pay_status=1).all()  # 未支付订单
        for i in order2:
            # print('=================>', i)
            data_ = {
                'shop_id': i.shop_id,
                'order_id': i.order_id,
                'order_num': i.total_count,
                'order_price': i.total_amount,
            }
            order_dishes = OrderGoods.objects.filter(order_id=i.order_id).all()
            dishess_list = []
            for j in order_dishes:
                # print('j==============>', j.id)
                data = {
                    'name': j.dishes.dishes_name,
                    'price': j.price,
                    'num': j.count,
                    'img': j.dishes.dishes_picture
                }
                # print('data===================>', data)
                dishess_list.append(data)
            data_['order_dishes'] = dishess_list
            order2_list.append(data_)
            # print('================>', order2_list)

        order3_list = []
        order3 = Order.objects.filter(user_id=user_id, pay_status=2).all()  # 未支付订单
        for i in order3:
            # print('=================>', i)
            data_ = {
                'shop_id': i.shop_id,
                'order_id': i.order_id,
                'order_num': i.total_count,
                'order_price': i.total_amount,
            }
            order_dishes = OrderGoods.objects.filter(order_id=i.order_id).all()
            dishes_list = []
            for j in order_dishes:
                # print('j==============>', j.id)
                data = {
                    'name': j.dishes.dishes_name,
                    'price': j.price,
                    'num': j.count,
                    'img': j.dishes.dishes_picture
                }
                # print('data===================>', data)
                dishes_list.append(data)
            data_['order_dishes'] = dishes_list
            order3_list.append(data_)
            # print('================>', order3_list)

        return Response(
            {'message': '获取成功', 'code': 200, 'order1': order1_list, 'order2': order2_list, 'order3': order3_list})



# 生产支付地址
class Pay(APIView):
    @check_login
    def post(self, request):
        # 获取前端数据
        order_id = request.data.get('order_id')
        address_id = request.data.get('address_id')
        user_id =request.user.id
        print("接收user", user_id)
        shopping_info = request.data.get('shopping_info')
        price = 0
        for i in shopping_info:
            price += (i['num'] * i['dishes_price'])
           # 收货地址
        if not address_id:
            return Response({'message': '请确认收货地址', 'code': 400})

        alipay = AlipayObject().alipay

        data = alipay.api_alipay_trade_page_pay(
            subject='购买外卖',  # 备注
            out_trade_no='%s' % order_id,  # 订单的编号
            total_amount=price,  # 价格
            return_url='http://localhost:8080/pay_callback'  # 支付完成后返回的地址
        )

        url = 'https://openapi.alipaydev.com/gateway.do?' + data
        print('支付地址', url)

        return Response({'msg': '生成支付地址成功', 'code': 200, 'url': url})

# 回调之后判断是否修改成功，修改支付状态
class Pay_callback(APIView):
    @check_login
    def put(self,request):
        date = request.data.get('data')
        sign = date.pop('sign')
        order_id = date.pop('out_trade_no')
        print('sign', sign)
        print('order_id',order_id)
        alipay = AlipayObject().alipay

        signature = alipay.verify(date, sign)
        print('signature', signature)
        if signature:
            pass
        else:
            order = Order.objects.get(order_id=order_id)
            print(order.pay_status)
            order.pay_status=1
            order.save()
            return Response({'code':200,'msg':'支付成功'})


    def post(self,request):
        order_id = request.data.get('order_id')
        print(order_id)
        Order.objects.get(order_id=order_id).delete()
        return Response({'code':200,'msg':'删除成功'})

class Pay_wancheng(APIView):
    def put(self,request):
        order_id = request.data.get('order_id')
        print(order_id)
        order = Order.objects.get(order_id=order_id)
        order.pay_status = 2
        order.save()
        return Response({'code': 200, 'msg': '完成订单'})

